package com.manage.service.impl;

import com.manage.dao.IUserDao;
import com.manage.domain.UserInfo;
import com.manage.service.IPasswordMigrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class PasswordMigrationServiceImpl implements IPasswordMigrationService {

    @Autowired
    private IUserDao userDao;

    private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    public int migrateAllToBCrypt() {
        List<UserInfo> all = userDao.findAllUsers();
        int updated = 0;
        for (UserInfo u : all) {
            String pwd = u.getPassword();
            if (pwd == null || pwd.startsWith("$2a$") || pwd.startsWith("$2b$") || pwd.startsWith("$2y$")) {
                continue; // already encoded or empty
            }
            String hash = encoder.encode(pwd);
            updated += userDao.updatePassword(u.getId(), hash);
        }
        return updated;
    }
}


